import { Repository } from 'typeorm';
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Coupon } from './entities/coupon.entity';
import { CreateCouponDto } from './dto/create-coupon.dto';
import { UpdateCouponDto } from './dto/update-coupon.dto';
import { UserService } from '../user/user.service';
import {
  ERROR_COUPON_NOT_FOUND,
  ERROR_USER_NOT_EXISTS,
} from '@/common/constant';

@Injectable()
export class CouponService {
  constructor(
    @InjectRepository(Coupon)
    private readonly couponRepository: Repository<Coupon>,
    private readonly userService: UserService,
  ) {}

  async Add(createCouponDto: CreateCouponDto) {
    const user = await this.userService.Detail(createCouponDto.userId);
    if (!user) throw new InternalServerErrorException(ERROR_USER_NOT_EXISTS);
    return await this.couponRepository.save(new Coupon(createCouponDto));
  }

  Delete(id: string) {
    return this.couponRepository.delete(id);
  }

  async Update(updateCouponDto: UpdateCouponDto) {
    const oldCoupon = await this.couponRepository.findOne({
      where: { id: updateCouponDto.id },
    });
    if (!oldCoupon)
      throw new InternalServerErrorException(ERROR_COUPON_NOT_FOUND);
    oldCoupon.status = updateCouponDto.status;
    return await oldCoupon.save();
  }

  Query(userId: string) {
    const coupons = this.couponRepository.find({
      where: { userId },
    });
    console.log("coupons", coupons);
    return coupons;
  }

  Detail(id: string) {
    return this.couponRepository.findOne({
      where: { id },
    });
  }
}
